from typing import Union

from fastapi import status
from fastapi.exceptions import HTTPException

from app.models.region_models import Region, RegionType
from app.schemas.region_schemas import (CreateRegionRequestSchema,
                                        RegionEditRequestSchema)


class RegionTools:
    """Класс предназначенный для соблюдения метода DRY при работе
    с регионами"""

    @staticmethod
    async def validate_region_request(
        request: Union[CreateRegionRequestSchema | RegionEditRequestSchema],
    ):
        """Метод отвечающий за валидацию запроса на создание/редактирования региона"""
        if (
            request.name is None
            or request.latitude is None
            or request.longitude is None
        ):
            raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST)

        if request.regionType:
            region_type = await RegionType.get_or_none(id=request.regionType)

            if region_type is None:
                raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)

        else:
            region_type = None

        region_with_same_latitude_and_longitude = await Region.filter(
            latitude=request.latitude, longitude=request.longitude
        )

        if len(region_with_same_latitude_and_longitude) > 0:
            raise HTTPException(status_code=status.HTTP_409_CONFLICT)

        return region_type
